define([ 'jquery', 'jquery_route', 'arttemplateUtil' ,'common','config','pageJs','md5','validform','wdatePicker','bootstrapselect','jquerycookie'], function($,
		jquery_route, arttemplateUtil,common,config,pageJs,md5  ) {
	
	$.controller("frequencyplanlogController", function($model, $tplHtml, $defobj,
			$modelobj, $paramobj, $this) {
		var param={};
		var initData = function(){
			// 查询地区
			common.ajax_request2('get','/api/seller/v1/frequencyPlanLog',param,function($data,$code){
				if($code==200){
					$defobj.data=$data;
				}
				$model($defobj);
				pageJs.setPage($data.pageNo,$data.totalPage,$data.totalCount,callback);
			});
		}
		//分页回调
		var callback = function(page){
			param.pageNo=page
			initData();
		}
		initData();
	});
	
	var frm1;
	var frm2;
	var userdata;
	// 代下单主加载控制器
	$.controller("proxyorderController", function($model, $tplHtml, $defobj,
			$modelobj, $paramobj, $this) {
		// 查询地区
		common.ajax_request2('get','/api/seller/v1/queryfzArea',{},function($data,$code){
			$defobj.fzarea=[];
			if($code==200){
				$defobj.fzarea=$data;
				$.each($data,function($fzindex,$fzdata){
					app.fzarea.fzareaid=$fzdata.parent_id;
					app.fzarea[$fzdata.id]=$fzdata.areaName;
					//alert($fzdata.areaName);
				});
			}
			$model($defobj);
			app.init();
		});
		
	});
	
	var app={
			// 初始化绑定事件
			searchflag:true,//当前搜索类型true areaid false area_nane
			fzareaid:0,// 福州的areaid
			fzarea:{},//福州地区的map obj 对象
			init:function(){
				
				// 设置商品信息
				common.ajax_request2('get','/api/seller/v1/queryServiceGoods',{},function($data,$code){
					if($code==200){
						var goodsbox=$("#proxyorderFrm .setp2 select[name=goodsid]");
						goodsbox.empty();
						goodsbox.append('<option value>请选择配送套餐</option>');
						$.each($data.records,function(index,data){
							if(data.label_type==2){
								goodsbox.append('<option value="'+data.id+'">'+data.goods_name+'</option>');
							}
						});
					}
				});

				
				var skudata={};
				var communityskudata={};
				$("#proxyorderFrm .setp2 select[name=goodsid]").on('change',function(){
					//重置小区sku
					communityskudata={};
					var _skuid=$("#proxyorderFrm .setp2 select[name=skuid]");
					_skuid.empty();
					_skuid.append('<option value>请选择规格类型</option>');
					if($(this).val()!=''){
						
						// 清空sku 价格 信息
						$('#pricetxt1').val('0');
						$('#pricetxt2').val('0');
						$('#pricetxt3').val('0');
						
						_skuid.attr('data-vip','false');
						// 设置商品是否在vip小区
//						common.ajax_request2('get','/api/seller/v1/queryCommunityByGoodsIdAndCommunityId',{goodsId:$(this).val(),comm_id:$('select[name=comm_id]').val()},function($data,$code){
//							if($code==200){
//								if(typeof $data != 'undefined' && typeof $data.length != 'undefined' && $data.length >0){
//									_skuid.attr('data-vip','true');
//								}
//							}
//						},false);
						
						//获取设置优惠小区价格
						common.ajax_request2('get','/api/seller/v1/queryGoodsCommunityPriceByGoodsIdCommunityId',{goodsId:$(this).val(),comm_id:$('select[name=comm_id]').val()},function($data,$code){
							if($code==200){
								$.each($data,function(index,data){
									communityskudata[data.goods_sku_id]=data;
								});
							}
						},false);
						
						common.ajax_request2('get','/api/seller/v1/queryGoodsSKU',{goodsid:$(this).val()},function($data,$code){
							if($code==200){
								$.each($data,function(index,data){
									skudata[data.id]=data;
									_skuid.append('<option value="'+data.id+'">'+data.delivery_name+'</option>');
								});
							}
						});

						var _delivery_time=$("#proxyorderFrm .setp2 select[name=delivery_time]");
						_delivery_time.empty();
						_delivery_time.append('<option value>请选择配送时间</option>');
						common.ajax_request2('get','/api/seller/v1/queryStoreFrequency',{goodsid:$(this).val()},function($data,$code){
							if($code==200){
								$.each($data,function(index,data){
									_delivery_time.append('<option value="'+data.id+'" data-times="'+data.times+'">'+data.name+'</option>');
								});
							}
						});
					}
				});
				
				$("#proxyorderFrm .setp2 select[name=skuid]").on('change',function(){
					if($(this).val()!=''){
						//vip小区价格设置
//						if('true' == $(this).attr('data-vip')){
//							$('#pricetxt1').val(skudata[$(this).val()].goods_price_after);
//							$('#pricetxt3').val(skudata[$(this).val()].goods_price_after);
//						}else{
//							$('#pricetxt1').val(skudata[$(this).val()].goods_price_before);
//							$('#pricetxt3').val(skudata[$(this).val()].goods_price_before);
//						}
						
						//指定的优惠小区价格
						//原价
						$('#pricetxt1').val(skudata[$(this).val()].goods_price_old);
						//售价
						if(typeof communityskudata[$(this).val()] == 'object' && typeof communityskudata[$(this).val()].special_price != ''){
							//如果sku存在那么使用小区价格
							$('#pricetxt3').val(communityskudata[$(this).val()].special_price);
						}else{
							$('#pricetxt3').val(skudata[$(this).val()].goods_price_before);
						}
						$('#pricetxt2').val('1');
						
						//设置是否能使用优惠券
						
						var _goodsid=$("#proxyorderFrm .setp2 select[name=goodsid]").val();
						var _skuid=$("#proxyorderFrm .setp2 select[name=skuid]").val();
						
//						
						common.ajax_request2('post','/api/seller/v1/checkDscDxdByGoods',{goods_id:_goodsid,goods_sku_id:_skuid},function($data,$code){
							if($code==200){
								if($data=='true'){
									$('#proxyorderFrm .setp2 select[name=pay_type] option[value="21"]').show();
								}else{
									$('#proxyorderFrm .setp2 select[name=pay_type] option[value="21"]').hide();
								}
							}
							//初始化兑换后输入框
							$('#giftcard').val('000000000000');
							$('#giftcard').parents('div.form-group').hide();
							//初始化支付方式选择框
							$('#proxyorderFrm .setp2 select[name=pay_type] option:first').attr('selected','selected');
						});
					}else{
						// 清空信息
						$('#pricetxt1').val('0');
						$('#pricetxt2').val('0');
						$('#pricetxt3').val('0');
					}
				});
				
				
				
				// 设置社区搜索功能
				$('#comm_idbasic2').selectpicker({
				      //liveSearch: true,
				      //maxOptions: 1
				 });
				// 绑定验证插件
				frm1=$("#proxyorderFrm .setp1").Validform({
					tiptype:4,
					postonce:true,
					isShowRight:false,
					datatype:{
						"checkphone": function(gets,obj,curform,regxp){
							$('#proceed_btn').hide();
							var regphone=/^1[3|4|5|7|8][0-9]{9}$/;
							if(regphone.test(gets)){
								if(gets != $('input[name=phoneexist]').val()){
									userdata=undefined;
									// 同步验证手机号码是否已存在
									var flag=false;
									obj.attr('errormsg','检测出错');
									common.ajax_request2('get','/api/seller/v1/checkUser',{phone:gets},function($data,$code,$business){
										if($code=='200'){
											if($data.length==1){
												userdata=$data[0];
												$('#proceed_btn').show();
												obj.attr('errormsg','该号码已注册过');
												$('input[name=phoneexist]').val('');
												flag = false;
											}else{
												$('[type-target=1]').show();
												flag = true;
											}
										}else{
											obj.attr('errormsg',$business.businessNote);
											flag = false;
										}
									},false);
									return flag;
								}
								return true;
							}
							$('input[name=phoneexist]').val('');
							obj.attr('errormsg','手机号码格式不对！');
							return false;
						}
					}
				});
				// 绑定验证插件
				frm2=$("#proxyorderFrm .setp2").Validform({
					tiptype:4,
					postonce:true,
					isShowRight:false,
					datatype:{}
				});

				// 继续注册
				$('#proceed_btn').on('click',function(){
					$('input[name=phoneexist]').val($('#proxyorderFrm input[name=phone]').val());
					$('#proxyorderFrm input[name=phone]').removeClass('Validform_error');
					var parent=$('#proxyorderFrm input[name=phone]').parent().find('.Validform_wrong');
					parent.html('');
					parent.removeClass('Validform_wrong');
					$(this).hide();
					var itrueName=$('#proxyorderFrm input[name=trueName]');
					if(itrueName.val()==''){
						if(typeof userdata.trueName != 'undefined' && userdata.trueName!=''){
							itrueName.val(userdata.trueName);
						}else if(typeof userdata.nick_name != 'undefined' && userdata.nick_name!=''){
							itrueName.val(userdata.nick_name);
						}
						frm1.check(false,itrueName);
					}
					$('[type-target=1]').hide();
				});
				
				var _searchbox_input=$('#proxyorderFrm #comm_idbasic2').parent().find('.dropdown-menu>.bs-searchbox>input');
				var commLoad=function($stxt){
					if(typeof $stxt =='undefined'){
						_searchbox_input.val('');
					}
					//如果内容为空且已经执行过areaid查询则不做任何操作
					if($stxt==''&&app.searchflag){
						return;
					}
					var _area_id=$('#proxyorderFrm select[name=area_id]').val();
					if(_area_id!=''){
						$.cookie('proxyorder_area_id', _area_id);
						_searchbox_input;
						var _param={area_id:_area_id};
						if(typeof $stxt != 'undefined' && $stxt!=''){
							//目前做area_name查询
							app.searchflag=false;
							_param.area_id=app.fzarea.fzareaid;
							_param.area_name=$stxt;
						}else{
							//目前做areaid查询
							app.searchflag=true;
						}
						common.ajax_request2('POST','/api/v1/queryCommunityByAreaId',_param,function($data,$code){
							if($code==200){
								var comm_idbasic2=$('#comm_idbasic2');
								comm_idbasic2.empty();
								comm_idbasic2.append('<option value>请选择小区</option>');
								$.each($data,function(index,data){
									comm_idbasic2.append('<option value="'+data.id+'" data-pid="'+data.pid+'"  data-subtext="'+app.fzarea[data.pid]+'">'+data.community_name+'</option>');
								});
								var  _comm_id=$.cookie('proxyorder_comm_id');
								if(typeof _comm_id !='undefined'){
									$('#proxyorderFrm #comm_idbasic2').find('option[value="'+_comm_id+'"]').attr("selected",true);
								}
								// 刷新搜索功能
								comm_idbasic2.selectpicker('refresh');
							}
						});
					}else{
						var comm_idbasic2=$('#comm_idbasic2');
						comm_idbasic2.empty();
						comm_idbasic2.append('<option value>请选择小区</option>');
						comm_idbasic2.selectpicker('refresh');
					}
				};
				
				// 从cookie 读取上次地区 并设置
				var _proxyorder_area_id=$.cookie('proxyorder_area_id');
				if(typeof _proxyorder_area_id !='undefined'){
					$('#proxyorderFrm select[name=area_id]').find('option[value="'+_proxyorder_area_id+'"]').attr("selected",true);
					commLoad();
				}
				
				// 地区选中事件
				$('#proxyorderFrm select[name=area_id]').on('change',function(){
					commLoad();
				});
				
				var tmpval='';
				_searchbox_input.keyup(function(e){
					if(tmpval!=$.trim($(this).val())){
						tmpval=$.trim($(this).val());
						commLoad(tmpval);
					}
				});
				
				
				// 社区选择框选中后验证
				$('#proxyorderFrm #comm_idbasic2').on('change',function(){
					var _comm_idbasic2=$('#proxyorderFrm #comm_idbasic2');
					var _areapid=_comm_idbasic2.find("option:selected").attr('data-pid');
					var _comm_id=_comm_idbasic2.val();
					$.cookie('proxyorder_comm_id', _comm_id);
					frm1.check(false,$(this));
					//选中地区下拉值
					$('#proxyorderFrm select[name=area_id]').find("option[value='"+_areapid+"']").attr("selected",true);  
				});
				// 社区选择框选中后验证
				$('#proxyorderFrm select[name=pay_type]').on('change',function(){
					if($(this).val()=='21'){
						$('#giftcard').val('');
						$('#giftcard').parents('div.form-group').show();
					}else{
						$('#giftcard').val('000000000000');
						$('#giftcard').parents('div.form-group').hide();
					}
				});

				
				//WdatePicker 日期控件问题优化
				window.WP={
						ordertime:function(){
							return WdatePicker({el:'ordertime',dateFmt:'yyyy-MM-dd HH:mm:ss'});
						},
						starttime:function(){
							var _wp;
							var _delivery_times=$("#proxyorderFrm .setp2 select[name=delivery_time]").find("option:selected").attr('data-times');
							if(typeof _delivery_times != 'undefined'){
								var _ordertime=$("#proxyorderFrm input[name=ordertime]").val();
								if(_ordertime != ''){
									common.ajax_request2('post','/api/seller/v1/queryDeliveryTime',{ordertime:_ordertime,frequencytime:_delivery_times},function($data,$code,$business){
										var _disabledDays=',,1,2,3,4,5,6,7,,';
										$.each(_delivery_times.split(','),function(_dindex,_ddata){
											_disabledDays=_disabledDays.replace(','+_ddata+',',',');
										});
										_disabledDays=_disabledDays.replace(',7,',',0,').replace(',,','').replace(',,','');
										if($code==200){
											// 当配送日期为1-7 是会出现只有一个逗号,增加判断
											if(_disabledDays==',' || _disabledDays==',,'){
												_wp={el:'starttime',minDate:$data};
											}else{
												_wp={el:'starttime',minDate:$data,disabledDays:_disabledDays.split(',')};
											}
										}else{
											_wp={el:'starttime',minDate:_ordertime,disabledDays:_disabledDays.split(',')};
										}
									},false);
								}else{
									window.layer.msg("请先选择订单时间");
									frm2.check(false,$("#proxyorderFrm input[name=ordertime]"));
								}
							}else{
								window.layer.msg("请先选择配送时间");
								frm2.check(false,$("#proxyorderFrm .setp2 select[name=delivery_time]"));
							}
							if(typeof _wp != 'undefined'){
								return WdatePicker(_wp);;
							}else{
								return false;
							}
						}
				};
				// 订单时间
				$("#proxyorderFrm input[name=ordertime]").attr('onclick',"WP.ordertime()");
//				$("#proxyorderFrm input[name=ordertime]").on('click',function(){
//					//WdatePicker({el:'ordertime',dateFmt:'yyyy-MM-dd HH:mm:ss'});
//				});
				
				// 起配时间
				$("#proxyorderFrm input[name=starttime]").attr('onclick',"WP.starttime()");
//				$("#proxyorderFrm input[name=starttime2]").on('click',function(){
//					var _delivery_times=$("#proxyorderFrm .setp2 select[name=delivery_time]").find("option:selected").attr('data-times');
//					if(typeof _delivery_times != 'undefined'){
//						var _ordertime=$("#proxyorderFrm input[name=ordertime]").val();
//						if(_ordertime != ''){
//							common.ajax_request2('post','/api/seller/v1/queryDeliveryTime',{ordertime:_ordertime,frequencytime:_delivery_times},function($data,$code,$business){
//								var _disabledDays=',,1,2,3,4,5,6,7,,';
//								$.each(_delivery_times.split(','),function(_dindex,_ddata){
//									_disabledDays=_disabledDays.replace(','+_ddata+',',',');
//								});
//								_disabledDays=_disabledDays.replace(',7,',',0,').replace(',,','').replace(',,','');
//								if($code==200){
//									// 当配送日期为1-7 是会出现只有一个逗号,增加判断
//									if(_disabledDays==',' || _disabledDays==',,'){
//										WdatePicker({el:'starttime',minDate:$data});
//									}else{
//										WdatePicker({el:'starttime',minDate:$data,disabledDays:_disabledDays.split(',')});
//									}
//								}else{
//									WdatePicker({el:'starttime',minDate:_ordertime,disabledDays:_disabledDays.split(',')});
//								}
//							});
//						}else{
//							window.layer.msg("请先选择订单时间");
//							frm2.check(false,$("#proxyorderFrm input[name=ordertime]"));
//						}
//					}else{
//						window.layer.msg("请先选择配送时间");
//						frm2.check(false,$("#proxyorderFrm .setp2 select[name=delivery_time]"));
//					}
//				});
				
				$('#proxyorderFrm .proxyorderNext').on('click',function(e){
					if(frm1.check()){
						common.loading();
						common.ajax_request2('post','/api/seller/v1/registerUser',{
							phone:$('input[name=phone]').val(),
							trueName:$('input[name=trueName]').val(),
							area_id:$('select[name=area_id]').val(),
							comm_id:$('select[name=comm_id]').val(),
							address:$('input[name=address]').val(),
							register_source:$('select[name=register_source]').val(),
							wxqq:$('input[name=wxqq]').val(),
							phoneexist:$('input[name=phoneexist]').val()
						},function($data,$code){
							frm2.resetForm();
							if($code=='200'){
								$('#proxyorderFrm input[name=userid]').val($data.userid);
								$('#proxyorderFrm input[name=addressid]').val($data.addressid);
								$('#proxyorderFrm input[name=newuser]').val($data.newuser);
								$('#proxyorderFrm .setp1').hide();
								$('#proxyorderFrm .setp2').show();
							}
							layer.closeAll('loading'); //关闭加载层
						});
					}
				});
				
				$('#proxyorderFrm .proxyorderSub').on('click',function(e){
					if(frm2.check()){
						common.loading();
						var _pay_type=$('#proxyorderFrm select[name=pay_type]').val();
						if(_pay_type=='21'){
							//平台礼券
							var _currentTimeMillis=new Date().getTime();
							var _coupon=$('#proxyorderFrm #giftcard').val();
							var _address_id=$('#proxyorderFrm input[name=addressid]').val();
							var _deliver_times=$('#proxyorderFrm select[name=delivery_time]').val();
							$('#proxyorderFrm #currentTimeMillis').val(_currentTimeMillis);
							$('#proxyorderFrm #exchange_code_md5').val(md5(_coupon));
							$('#proxyorderFrm #sign_data').val(app.sign_data($.cookie("token"),_currentTimeMillis,_coupon,_address_id,_deliver_times));
						}else{
							$('#proxyorderFrm #currentTimeMillis').val('');
							$('#proxyorderFrm #exchange_code_md5').val('');
							$('#proxyorderFrm #sign_data').val('');
						}
						// 从
						var paramobj=$('#proxyorderFrm form').serializeArray();
						$.each(paramobj,function(index,datap){
							if(typeof datap !='undefined' && typeof datap.name == 'string' && datap.name == 'giftcard'){
								paramobj.splice(index,1);
								return;
							}
						});
						common.ajax_request2('post','/api/seller/v1/proxyOrder',paramobj,function($data,$code,$business){
							if($code==200){
								// 跳转到成功页面
								alert("代下单成功");
								location.hash='?_r='+Math.random()+'#order/proxyorder';
							}else{
								alert(rep_businessNo($business.businessNote));
							}
							layer.closeAll('loading'); //关闭加载层
						});
					}
				});
				
				$('#proxyorderFrm .imputOrder').on('click',function(){
					common.ajax_request2('get','/api/seller/v1/imputOrder',{},function($data,$code,$business){
						if($code=='200'){
							alert(JSON.stringify($data));
						}else{
							alert(rep_businessNo($business.businessNote));
						}
					});
				});
				
			},
			//生成签名串
			sign_data:function(token,currentTimeMillis,coupon,address_id,deliver_times){
				return md5(token+''+currentTimeMillis+''+coupon+''+address_id+''+deliver_times);
			}
	};
});